// ****************************************************************
// Copyright 2012, Stephan Burguchev
// e-mail: me@sburg.net
// ****************************************************************
// *
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace Updater.FeedBuilder
{
    public class NAntProperties
    {
        private NAntProperties()
        {
        }

        public string Filename { get; private set; }

        public Dictionary<string, string> Properties { get; private set; }

        public static NAntProperties Load(string filename)
        {
            if (filename == null)
            {
                throw new ArgumentNullException("filename");
            }

            var nAntProperties = new NAntProperties();
            nAntProperties.Filename = filename;

            XDocument xdoc = XDocument.Load(filename);
            XNamespace ns = xdoc.Root.GetDefaultNamespace();
            nAntProperties.Properties = xdoc.Root.Elements(ns + "property")
                                            .ToDictionary(k => k.Attribute("name").Value, v => v.Attribute("value").Value);

            return nAntProperties;
        }

        public void Save()
        {
            XDocument xdoc = XDocument.Load(this.Filename);
            XNamespace ns = xdoc.Root.GetDefaultNamespace();
            foreach (var property in this.Properties)
            {
                XElement element = xdoc.Root.Elements(ns + "property")
                                       .FirstOrDefault(e => e.Attribute("name").Value == property.Key);
                if (element == null)
                {
                    var newElement = new XElement(ns + "property");
                    newElement.SetAttributeValue("name", property.Key);
                    newElement.SetAttributeValue("value", property.Value);
                    newElement.SetAttributeValue("overwrite", "false");
                    xdoc.Root.Add(newElement);
                }
                else
                {
                    element.SetAttributeValue("value", property.Value);
                }
            }

            string s = xdoc.ToString();
            xdoc.Save(this.Filename);
        }
    }
}
